package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户喜欢服务接口实现类
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private FriendApi friendApi;

    /**
     * 喜欢 或 不喜欢 记录
     *
     * @param userLike
     * @return
     */
    @Override
    public boolean save(UserLike userLike) {
        Long userId = userLike.getUserId();//当前登录用户id
        Long likeUserId = userLike.getLikeUserId();//喜欢的用户id
        Boolean isLike = userLike.getIsLike();//是否喜欢 左滑右滑
        long nowTime = System.currentTimeMillis();//时间
        //1.根据当前登录用户id 喜欢的用户id 查询记录是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        if (mongoTemplate.exists(query, UserLike.class)) {
            //2.存在 则更新记录
            Update update = new Update();
            update.set("isLike", isLike);//是否喜欢
            update.set("updated", nowTime);//更新时间
            mongoTemplate.updateFirst(query, update, UserLike.class);
        } else {
            //3.不存在 则保存记录
            userLike.setCreated(nowTime);
            userLike.setUpdated(nowTime);
            mongoTemplate.insert(userLike);
        }
        //4.如果isLike=true，判断对方是否喜欢登录用户
        if (isLike) {
            Query query2 = new Query();
            query2.addCriteria(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId).and("isLike").is(true));
            UserLike ul = mongoTemplate.findOne(query2, UserLike.class);
            //4.1如果喜欢 将好友关系添加好友表 return true;
            if (mongoTemplate.exists(query2, UserLike.class)) {
                friendApi.makeFriends(userId, likeUserId);
                return true;
            }
        }
        return false;
    }

    /**
     * 分页查询我关注的用户
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<UserLike> findMyLove(Long page, Long pageSize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("isLike").is(true));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);
        long start = (page - 1) * pageSize;
        //每页查询几条
        query.limit(pageSize.intValue());
        //跳过1条数据
        query.skip(start);
        query.with(Sort.by(Sort.Direction.DESC, "created"));
        return new PageResult<>(page,pageSize,count,userLikes);

    }

    /**
     * 分页查询相互喜欢列表
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<UserLike> eachLove(Long page, Long pageSize, Long userId) {
        //定义返回PageResult<UserLike>
        PageResult<UserLike> pageResult = new PageResult<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("isLike").is(true));
        //1查询总记录数
        long counts = mongoTemplate.count(query, UserLike.class);
        long start = (page-1)*pageSize;
        //2查询当前页面需要展示的数据
        List<UserLike> userLikeList = new ArrayList<>();
        List<UserLike> userLikeList1 = new ArrayList<>();
        long counts2 =0;
        if(counts > start) { //20 > 27
            //构造分页limit 0,3
            query.limit(pageSize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            query.with(Sort.by(Sort.Direction.DESC, "userId"));
            userLikeList = mongoTemplate.find(query, UserLike.class);
            for (UserLike userLike : userLikeList) {
                save(userLike);//调用加为好友的方法
            }
            if (CollectionUtils.isNotEmpty(userLikeList)) {
                Query query1 = new Query();
                List<Long> likeUserIds = userLikeList.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
                query1.addCriteria(Criteria.where("userId").in(likeUserIds).and("likeUserId").is(userId).and("isLike").is(true));
                userLikeList1 = mongoTemplate.find(query1, UserLike.class);
                counts2 = mongoTemplate.count(query1, UserLike.class);
            }
        }
        return new PageResult<>(page, pageSize, counts2, userLikeList1);
    }

    /**
     * 取消喜欢
     *
     * @param userId
     * @param uid
     */
    @Override
    public void deleteLove(Long userId, Long uid) {

        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(uid));
        Update update = new Update();
        update.set("isLike",false);
        mongoTemplate.updateFirst(query,update,UserLike.class);
    }


    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     */
    @Override
    public Integer countById(Long userId) {

        Long count = mongoTemplate.count(new Query(Criteria.where("userId").is(userId)), Friend.class);
        return Integer.valueOf(count.intValue());
    }

    @Override
    public Integer findByUserId(Long userId) {
     Long  count =mongoTemplate.count(new Query(Criteria.where("userId").is(userId).and("isLike").is(true)),UserLike.class);
        return Integer.valueOf(count.intValue());
    }

    @Override
    public Integer findByLikeUserId(Long userId) {
        Long  count =  mongoTemplate.count(new Query(Criteria.where("likeUserId").is(userId).and("isLike").is(true)),UserLike.class);
        return Integer.valueOf(count.intValue());
    }

    /**
     * 我的访客中需要个isLike属性
     * @param userId
     * @return
     */
    @Override
    public List<UserLike> findByIdss(Long userId,List<Long> visitorsIds) {
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(visitorsIds));
        return mongoTemplate.find(query, UserLike.class);
    }

    /**
     * 粉丝列表分页查询
     */
    @Override
    public PageResult<UserLike> fansListPage(Long page, Long pageSize, Long userId) {
        //定义返回PageResult<UserLike>
        PageResult<UserLike> pageResult = new PageResult<>();
        //查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(userId).and("isLike").is(true));
        //1查询总记录数
        long counts = mongoTemplate.count(query, UserLike.class);
        long start = (page - 1) * pageSize;
        //2查询当前页面需要展示的数据
        List<UserLike> userLikeList = new ArrayList<>();
        if (counts > start) { //20 > 27
            //构造分页limit 0,3
            query.limit(pageSize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            //query.with(PageRequest.of(page,pageSize));
            query.with(Sort.by(Sort.Direction.DESC, "likeUserId"));
            userLikeList = mongoTemplate.find(query, UserLike.class);
        }
        //获取当前用户的所有粉丝ids集合
        List<Long> collect = userLikeList.stream().map(UserLike::getUserId).collect(Collectors.toList());
        //获取 当前用户 同时也喜欢粉丝的ids集合
        Query query1=new Query();
        query1.addCriteria(Criteria.where("userId").is(userId).and("likeUserId").in(collect).and("isLike").is(true));
        List<UserLike> userLikeList1 = mongoTemplate.find(query1, UserLike.class);//获取 当前用户和粉丝 相互喜欢 集合
        List<Long> collect1 = userLikeList1.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        //求集合差集CollectionUtil.subtract()
        Collection<Long> subtract = CollectionUtil.subtract(collect, collect1);

        Map<Long, UserLike> collect2 = userLikeList.stream().collect(Collectors.toMap(UserLike::getUserId, UserLike -> UserLike));
        //遍历
        for (Long aLong : subtract) {
            UserLike userLike = collect2.get(aLong);
            userLike.setIsLike(false);
            collect2.put(aLong,userLike);
        }
        //获取所有粉丝userLike的集合
        List<UserLike> collect3 = collect2.values().stream().collect(Collectors.toList());
        return new PageResult<UserLike>(page, pageSize, counts, collect3);
    }

    /**
     * 粉丝喜欢 isLike
     * @param
     * @return
     */
    @Override
    public void loveFansList(Long likeUserId, Long userId) {
        long nowTime = System.currentTimeMillis();//获取当前时间
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId));
        if (mongoTemplate.exists(query, UserLike.class)) {
            Update update = new Update();
            update.set("isLike", true);//是否喜欢
            update.set("updated", nowTime);//更新时间
            mongoTemplate.updateFirst(query, update, UserLike.class);
        } else {
            UserLike ul = new UserLike();
            //3.不存在 则保存记录
            ul.setUserId(userId);
            ul.setLikeUserId(likeUserId);
            ul.setIsLike(true);
            ul.setCreated(nowTime);
            ul.setUpdated(nowTime);
            mongoTemplate.insert(ul);
        }
        //4.如果isLike=true，判断对方是否喜欢登录用户
        friendApi.makeFriends(userId, likeUserId);
    }














}
